package com.feel.common.utils;

import com.google.gson.Gson;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @Author: zz
 * @Description:
 * @Date: 2:26 AM 6/14/19
 * @Modified By
 */
@Configuration
@Component
public class JWTUtils {



    @Value("${wx.app-secret}")
    private String secret;

    @Value("${wx.expireTime}")
    private long expire;

    @Value("${wx.header}")
    private String header;


    public String createTokenByObj(Map<String, Object> map){
        return createJWT(map , getSecret());
    }

    public Claims getClaimByToken(String token) {
        return parseJWT(token , getSecret());
    }


    /**
     * 解密
     * @param jsonWebToken
     * @param base64Security
     * @return
     */
    public static Claims parseJWT(String jsonWebToken, String base64Security) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(base64Security.getBytes())
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 前三个参数为自己用户token的一些信息比如id，权限，名称等。不要将隐私信息放入（大家都可以获取到）
     * @param map
     * @param base64Security
     * @return
     */
    public static String createJWT(Map<String, Object> map, String base64Security) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setPayload(new Gson().toJson(map))
                .signWith(signatureAlgorithm,base64Security.getBytes())
                ; //估计是第三段密钥
        //生成JWT
        return builder.compact();
    }




    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public long getExpire() {
        return expire;
    }

    @Value("${wx.expireTime}")
    public void setExpire(long expire) {
        this.expire = expire;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }


    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    public static void main(String[] args) {
//        Map<String, Object> map = new HashMap<String, Object>();
//        UserToken userToken = UserToken.builder()
//                .userId(123l)
//                .openid("asddfg")
//                .type("wem")
//                .build();
//
//        map.put("province", "898765");
//        map.put("city", "898765");
//        map.put("appkey", "HMu1H/cmyKDOiHv41Y9lLROuOlOo+PPG8F4/RotRmNc=");
//        map.put("exp", DateUtils.getNowDate());
//
//        //密钥
//        String keyt = "83fb1718dbfbe3402e23ef521bbcacad";
//        String token = JWTUtils.createJWT(MapUtils.obj2Map(userToken), keyt);
//        System.out.println("JWT加密的结果："+ token);
//        Claims claims = parseJWT(token, keyt);
//        long userid = Long.parseLong(claims.get("userId" , String.class));
//        System.out.println("JWT解密的结果："+ claims.get("userId"));
    }
}
